package com.sxpi.upload.service;

import cn.hutool.core.util.IdUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.HashMap;

/**
 * @Author: 董伟豪
 * @Date: 2022/10/19 10:27
 */
@Service
@Slf4j
public class CosUploadService {

    @Value("${cos.upload.appId}")
    private String appId;
    @Value("${cos.upload.secretId}")
    private String secretId;
    @Value("${cos.upload.secretKey}")
    private String secretKey;
    @Value("${cos.upload.regionPublic}")
    private String regionPublic;
    @Value("${cos.upload.bucketPublic}")
    private String bucketPublic;

    /**
     * 获取访问公有存储桶的连接
     */
    private COSClient getCosPublicClient() {
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        ClientConfig clientConfig = new ClientConfig(new Region(regionPublic));
        clientConfig.setHttpProtocol(HttpProtocol.https);
        COSClient cosClient = new COSClient(cred, clientConfig);
        return cosClient;
    }

    /**
     * 向公有存储桶上传文件
     * path=xxb
     */
    public HashMap uploadPublicFile(MultipartFile file, String path) throws IOException {
        // 上传文件的名字
        String fileName = file.getOriginalFilename();
        // 文件后缀名
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        // 避免重名图片在云端覆盖，所以用UUID作为文件名
        path += "/" + IdUtil.simpleUUID() + fileType;

        // 元数据信息
        ObjectMetadata meta = new ObjectMetadata();
        meta.setContentLength(file.getSize());
        meta.setContentEncoding("UTF-8");
        meta.setContentType(file.getContentType());

        // 向存储桶中保存文件
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketPublic, path, file.getInputStream(), meta);
        // 标准存储
        putObjectRequest.setStorageClass(StorageClass.Standard);

        // 开始远程上传
        COSClient client = getCosPublicClient();
        PutObjectResult putObjectResult = client.putObject(putObjectRequest);

        // 合成外网访问地址
        HashMap map = new HashMap();
        // 完整路径
        map.put("url", "https://" + bucketPublic + ".cos." + regionPublic + ".myqcloud.com" +"/"+ path);
        // 相对路径
        map.put("path", path);
        map.put("oldname", file.getOriginalFilename());
        map.put("ext",fileType);
        map.put("filesize",file.getSize());



// 如果保存的是图片，用数据万象服务对图片内容审核
//        if (List.of(".jpg", ".jpeg", ".png", ".gif", ".bmp").contains(fileType)) {
//            //审核图片内容
//            ImageAuditingRequest request = new ImageAuditingRequest();
//            request.setBucketName(bucketPublic);
//            request.setDetectType("porn,terrorist,politics,ads"); //辨别黄色、暴利、政治和广告内容
//            request.setObjectKey(path);
//            ImageAuditingResponse response = client.imageAuditing(request); //执行审查
//
//            if (!response.getPornInfo().getHitFlag().equals("0")
//                    || !response.getTerroristInfo().getHitFlag().equals("0")
//                    || !response.getPoliticsInfo().getHitFlag().equals("0")
//                    || !response.getAdsInfo().getHitFlag().equals("0")
//            ) {
//                //删除违规图片
//                client.deleteObject(bucketPublic, path);
//                throw new PugBusinessException("图片内容不合规");
//            }
//        }
        client.shutdown();
        return map;
    }

    public static void main(String[] args) {
        CosUploadService cosUploadService = new CosUploadService();
        cosUploadService.createBucket("auth");
    }


    /**
     * 创建桶的方法
     * @param bucket
     */
    public void createBucket(String bucket) {
        CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucket + "-" + appId);
        // 设置 bucket 的权限为 Private(私有读写), 其他可选有公有读私有写, 公有读写
        createBucketRequest.setCannedAcl(CannedAccessControlList.Private);
        COSClient cosClient = getCosPublicClient();
        cosClient.createBucket(createBucketRequest);
    }

    /**
     * 刪除公有存储桶的文件 /xxb/a.jpg
     */
    public void deletePublicFile(String[] pathes) {
        // 获取共有桶连接
        COSClient client = getCosPublicClient();
        for (String path : pathes) {
            client.deleteObject(bucketPublic, path);
        }
        client.shutdown();
    }
}
